package org.emavaj.sanguosha.model.card.resource;

import java.util.HashMap;
import java.util.Map;

import org.emavaj.common.collection.TwoWayMap;
import org.emavaj.sanguosha.model.card.ICard;
import org.emavaj.sanguosha.model.exception.SGSException;

/**
 * 
 * @author eMavaj
 * 
 */
public class CardResHelper {

	private static Map<String, CardResInfo> cardResInfo = new HashMap<String, CardResInfo>();
	
	private static TwoWayMap<String, Integer> cardStr2CodeMap = new TwoWayMap<String, Integer>();

	public static boolean addCardResInfo(String name, String filename,
			String description) {
		if (!cardResInfo.containsKey(name)) {
			cardResInfo.put(name, new CardResInfo(name, filename, description));
			return true;
		} else {
			return false;
		}
	}

	public static String getCardFilename(String name) {
		CardResInfo info = cardResInfo.get(name);
		if (info == null) {
			return null;
		} else {
			return info.getFilename();
		}
	}

	public static String getCardHtmlDesciption(String name) {
		CardResInfo info = cardResInfo.get(name);
		if (info == null) {
			return null;
		} else {
			return "<html>" + info.getDescription().replaceAll("\\n", "<p>")
					+ "</HTML>";
		}
	}

	public static String getContentCode() {
		// return JSONUtil.convertToString(cardResInfo);
		StringBuffer buffer = new StringBuffer();
		for (CardResInfo info : cardResInfo.values()) {
			buffer.append(":").append(info.toString());
		}
		return buffer.toString().substring(1);
	}

	public static void convertFromCode(String jsonStr) {
		// cardResInfo = ((Map<String, CardResInfo>) JSONUtil.convertToObject(
		// jsonStr, Map.class));
		if (cardResInfo.size() == 0) {
			String[] parts = jsonStr.split(":");
			int len = parts.length;
			for (int i = 0; i < len;) {
				String name = parts[i];
				++i;
				String filename = parts[i].replace("|", ":");
				++i;
				String description = parts[i].replace("|", ":");
				++i;
				cardResInfo.put(name, new CardResInfo(name, filename,
						description));
			}
		}
	}
	
	static {
		cardStr2CodeMap.put("黑桃", ICard.PATTERN_SPADE);
		cardStr2CodeMap.put("梅花", ICard.PATTERN_CLUB);
		cardStr2CodeMap.put("红桃", ICard.PATTERN_HEART);
		cardStr2CodeMap.put("方块", ICard.PATTERN_DIAMOND);
	}
	
	public static int getSuitCode(String pattern) {
		Integer suit = cardStr2CodeMap.getValue(pattern);
		if (suit == null) {
			throw new SGSException("花色 to code 错误");
		} else {
			return suit;
		}
	}
	
	public static String getSuitString(int suit) {
		String suitStr = cardStr2CodeMap.getKey(suit);
		if (suitStr == null) {
			throw new SGSException("code to 花色 错误");
		} else {
			return suitStr;
		}
	}
}
